package com.sky.web.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageDTO;
import com.sky.entity.Dish;
import com.sky.result.PageBean;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 分页查询
    @GetMapping("/page")
    public Result findByPage(DishPageDTO dto) {
        PageBean<DishVO> pageBean = dishService.findByPage(dto);
        return Result.success(pageBean);
    }

    // 新增菜品
    @PostMapping
    public Result save(@RequestBody DishDTO dto) {
        dishService.save(dto);
        // 清理缓存
        redisTemplate.delete( "DISH:"+dto.getCategoryId());
        return Result.success();
    }

    // 回显菜品
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Long id) {
        DishVO dishVO = dishService.findById(id);
        return Result.success(dishVO);
    }

    // 修改菜品
    @PutMapping
    public Result update(@RequestBody DishDTO dto) {
        dishService.update(dto);
        // 清理缓存
        redisTemplate.delete( redisTemplate.keys("DISH*"));
        return Result.success();
    }

    // 删除菜品
    @DeleteMapping
    public Result deleteByIds(@RequestParam List<Long> ids) {
        dishService.deleteByIds(ids);
        // 清理缓存
        redisTemplate.delete( redisTemplate.keys("DISH*"));
        return Result.success();
    }

    //起售 禁售
    @PostMapping("/status/{status}")
    public Result startOrStop(Long id, @PathVariable("status") Integer status) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();

        dishService.startOrStop(dish);

        // 清理缓存
        redisTemplate.delete( redisTemplate.keys("DISH*"));

        return Result.success();
    }

    // 查询菜品列表
    @GetMapping("/list")
    public Result findList(DishPageDTO dto) {
        List<DishVO> list = dishService.findList(dto);
        return Result.success(list);
    }
}
